package com.dps.omc.utils;

import com.dps.omc.model.SqlWarnKeyWord;
import com.dps.omc.service.ISqlWarnKeyWordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**  上传危险关键字检查
 * Created by lip on 2016-04-20.
 */

@Component
public class SqlWarnAnalyzer implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger logger = LoggerFactory.getLogger(SqlWarnAnalyzer.class);
    @Autowired
    private ISqlWarnKeyWordService sqlWarnKeyWordService;

    private static Map<String,String> map;

    public void reload(){
        loadMap();
    }

    private void loadMap(){
        logger.info("=========初始化SQL危险关键字开始========");
        map = new HashMap<String, String>();
        List<SqlWarnKeyWord> words = sqlWarnKeyWordService.findAll();
        for(SqlWarnKeyWord word:words)
        {
            map.put(word.getKeyWord(),word.getKeyWord());
        }
        logger.info("=========初始化SQL危险关键字完毕========");
    }

    public boolean analyse(MultipartFile file) throws Exception
    {
        String content = this.getContent(file);
        return this.analyse(content);
    }

    private boolean analyse(String content)
    {
        content = content.toLowerCase();
        for(String key:map.keySet())
        {
            if(content.contains(key))
            {
                return true;
            }
        }
        return false;
    }

    private String getContent(MultipartFile file) throws Exception {

        InputStream is = file.getInputStream();
        byte[] b = readStream(is);
        String str = new String(b);
        return str;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        int count = 0;
        while (count == 0) {
            count = inStream.available();
        }
        byte[] b = new byte[count];
        inStream.read(b);
        return b;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        loadMap();
    }
}
